package top.ruanlitao.shortlink.admin.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import top.ruanlitao.shortlink.admin.common.biz.user.UserContext;
import top.ruanlitao.shortlink.admin.common.convention.result.Result;
import top.ruanlitao.shortlink.admin.dao.entity.GroupDO;
import top.ruanlitao.shortlink.admin.dao.mapper.GroupMapper;
import top.ruanlitao.shortlink.admin.remote.ShortLinkActualRemoteService;
import top.ruanlitao.shortlink.admin.remote.dto.req.ShortLinkRecycleBinPageReqDTO;
import top.ruanlitao.shortlink.admin.remote.dto.resp.ShortLinkPageRespDTO;
import top.ruanlitao.shortlink.admin.service.RecycleBinService;

import java.util.List;

/**
 * 回收站接口是实现层
 */
@Service
@RequiredArgsConstructor
public class RecycleBinServiceImpl implements RecycleBinService {

    // 短链接中台远程调用服务（使用 SpringCloud OpenFeign）
    private final ShortLinkActualRemoteService shortLinkActualRemoteService;

    private final GroupMapper groupMapper;

    @Override
    public Result<Page<ShortLinkPageRespDTO>> pageRecycleBinShortLink(ShortLinkRecycleBinPageReqDTO requestParam) {
        // 查询当前用户的所有分组 gidList
        LambdaQueryWrapper<GroupDO> queryWrapper = Wrappers.lambdaQuery(GroupDO.class)
                .eq(GroupDO::getUsername, UserContext.getUsername())
                .orderByDesc(GroupDO::getSortOrder)
                .orderByAsc(GroupDO::getUpdateTime);
        // 查询到分组信息
        List<GroupDO> groupDOList = groupMapper.selectList(queryWrapper);
        if (CollUtil.isNotEmpty(groupDOList)) {
            // 将 gidList 加入到查询参数
            requestParam.setGidList(groupDOList.stream().map(GroupDO::getGid).toList());
        }
        // 调用中台的查询接口返回数据
        return shortLinkActualRemoteService.pageRecycleBinShortLink(requestParam);
    }
}
